﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OpenPhotoAlbum.DbAccess;

namespace OpenPhotoAlbum.BusinessLogics
{
	public class CommentManager
	{
		#region Singleton

        private static readonly CommentManager _instance = new CommentManager();

		private CommentManager() { }

		public static CommentManager Instance
        {
            get { return _instance; }
        }

        #endregion

		public string GetCommentOwner(Guid commentId)
		{
			DbLinqClassesDataContext context = new DbLinqClassesDataContext();
			var results = from c in context.Comments
						  where c.CommentId.Equals(commentId)
						  select c.Photo.Album.User.UserName;
			return results.First();
		}

		public IEnumerable<Comment> GetComments(Guid photoId)
		{
			DbLinqClassesDataContext context = new DbLinqClassesDataContext();
			return GetComments(context, photoId);
		}

		public IEnumerable<Comment> GetComments(DbLinqClassesDataContext context, Guid photoId)
		{
			var results = from c in context.Comments
						  where c.PhotoId.Equals(photoId)
						  orderby c.CommentDateTime descending
						  select c;
			return results;
		}

		public void AddComment(Guid? userId, Guid photoId, DateTime dateTime, string ipAddress, string content)
		{
			Comment comment = new Comment();
			comment.CommentId = Guid.NewGuid();
			comment.UserId = userId;
			comment.PhotoId = photoId;
			comment.CommentDateTime = dateTime;
			comment.IpAddress = ipAddress;
			comment.CommentContent = content;

			DbLinqClassesDataContext context = new DbLinqClassesDataContext();
			context.Comments.InsertOnSubmit(comment);
			context.SubmitChanges();

			ActionManager.Instance.AddComment(content, photoId);
		}

		public void DeleteComment(Guid commentId)
		{
			DbLinqClassesDataContext context = new DbLinqClassesDataContext();
			var results = from c in context.Comments
						  where c.CommentId.Equals(commentId)
						  select c;
			if (results == null || results.Count() == 0) { return; }

			context.Comments.DeleteOnSubmit(results.First());
			context.SubmitChanges();
		}

		public void DeleteComments(DbLinqClassesDataContext context, IEnumerable<Comment> comments)
		{
			context.Comments.DeleteAllOnSubmit(comments);
		}
	}
}
